<script setup lang="ts">
  import { ref, onActivated, watch, onDeactivated } from 'vue';
  const imgsmap = JSON.parse(localStorage.getItem('tokensImgsMap') as string);
  import { useRouter } from 'vue-router';
  import TradeOrders from './components/TradeOrders.vue';
  import TradeHistory from './components/TradeHistory.vue';
  import { NotifyWarn, NotifySuccess } from '/@/utils';
  import TradePopup from './components/TradePopup.vue';
  import { useRequest } from 'vue-request';
  import { jiadesocketio } from '/@/hooks/index';
  import Kline from './components/Kline.vue';
  const { getUserId } = useUserId();
  import {
    getSecondscontract,
    secondContractBetting,
    getBalances,
    getUserInfo,
    queryTradeList,
    queryOpenPrice,
  } from '/@/apis/userApi';
  import { i18nTranslate } from '/@/i18n';
  import { useUserId } from '/@/hooks';
  const activedSeendData = ref<{ [xx: string]: any }>({});
  const qiehuan = ref<{ [xx: string]: any }>({});
  const lastData = ref<{ [xx: string]: any }>({});
  const router = useRouter();
  const assetsBalance = ref(0);
  const orderTimes = ref();
  const jiadesocket = ref();
  const mapklinetype = ref<{ [xx: string]: any }>({
    '30s': '30s',
    '1m': '60s',
    '5m': '300s',
    '15m': '15m',
    '1h': '1h',
    '48h': '48h',
  });
  const dangqianjiage = ref('');
  const openPrice = ref<{ [xx: string]: any }>({});
  const userInfo = ref();
  function changePopup(val: any, isInit?: boolean) {
    if (isInit) {
      if (qiehuan.value.name == val.name) return;
      qiehuan.value = val;
      lastData.value = val;
      secondscontract();
    }
  }
  let timers = ref();
  let getdangqianjiagetimers = ref();
  let listTimer = ref();
  onDeactivated(() => {
    clearInterval(timers.value);
    timers.value = null;
    clearInterval(getdangqianjiagetimers.value);
    getdangqianjiagetimers.value = null;
    clearInterval(listTimer.value);
    listTimer.value = null;
  });
  function timer() {
    timers.value = setInterval(sendjiadeline, 1000);
    getdangqianjiagetimers.value = setInterval(getdangqianjiage, 1000);
  }
  function isContent() {
    return jiadesocket.value.socketver.readyState == 1;
  }
  onActivated(() => {
    jiadesocket.value = jiadesocketio();
    jiadesocket.value.getMixinWs(customSocketFunction);
    secondscontract();
    getBalance();
    timer();
  });
  function queryOpenPriceparms(value: string) {
    useRequest(queryOpenPrice, {
      defaultParams: [{ pairsNames: value }],
      onSuccess(data: any) {
        if (data) {
          for (const key in data) {
            let item = data[key];
            let openPricegd = JSON.parse(item).data;
            openPrice.value[key] = openPricegd;
          }
        }
      },
    });
  }
  function queryTradeListparms() {
    if (!(qiehuan.value.nickName || qiehuan.value.name)) {
      return;
    }
    useRequest(queryTradeList, {
      defaultParams: [{ pairsName: qiehuan.value.nickName || qiehuan.value.name }],
      onSuccess(data: any) {
        let customArr: any[] = [];
        customArr = data.filter((item: { [key: string]: any }) => {
          return item.orderType <= secondscontractList.value.length;
        });
        tradeList.value = customArr.slice(0, 13);
        console.log(tradeList.value);
      },
    });
  }
  const secondscontractList = ref<{ [xx: string]: any }[]>([]);
  function secondscontract() {
    useRequest(getSecondscontract, {
      onSuccess(data: any) {
        secondscontractList.value = data;
        activedSeendData.value = secondscontractList.value[0];
        queryTradeListparms();
      },
    });
  }
  function zhorderType(val: 1 | 2 | 3 | 4 | 5 | 6) {
    let orderType = ['60s', '90s', '120s', '180s'];
    return orderType[val - 1];
  }
  function getdangqianjiage() {
    if (qiehuan.value.name && qiehuan.value.type === 'CONTRACT') {
      if (!isContent()) return;
      jiadesocket.value.socketver.send(
        `cryptoCurrency-["${qiehuan.value.name.split('/').join('')}"]`,
      );
    }
  }
  const currentPrice = ref<{ [xx: string]: any }>({});
  function customSocketFunction(
    socketmessage:
      | { method: string }[]
      | {
          initKline?: string;
          pairName: string;
          timeType?: string;
          currentPrice?: string;
          method?: string;
          datas?: string;
          symbols?: string;
        },
  ) {
    // 右边的交易列表
    if (Array.isArray(socketmessage)) {
      console.log(socketmessage);

      socketmessage.forEach((item: { [xx: string]: any }) => {
        if (item.orderType <= secondscontractList.value.length) {
          tradeList.value.unshift(item);
          tradeList.value = tradeList.value.slice(0, 13);
        }
      });
    }
    // 币
    else if (socketmessage.method == 'cryptoCurrency') {
      currentPrice.value[JSON.parse(socketmessage.symbols as string)[0]] = Number(
        JSON.parse(socketmessage.datas as string)[0].price,
      ).toFixed(4);

      if (
        JSON.parse(socketmessage.symbols as string)[0] ==
        (qiehuan.value.nickName || qiehuan.value.name).split('/').join('')
      ) {
        dangqianjiage.value = Number(JSON.parse(socketmessage.datas as string)[0].price).toFixed(4);
      }
    }
  }
  function sendjiadeline() {
    // 获取当前需要购买的合约的实时价格
    // flag 1是币 0是外汇
    if (!isContent()) return;
    if (qiehuan.value.name && qiehuan.value.type === 'CONTRACT') {
      jiadesocket.value.socketver.send(
        `cryptoCurrency-["${(qiehuan.value.nickName || qiehuan.value.name).split('/').join('')}"]`,
      );
    }
    jiadesocket.value.socketver.send(`TRADE-${qiehuan.value.nickName || qiehuan.value.name}-1m`);
  }
  const num = ref();
  const topTabActive = ref(0);
  const tab_active = ref(0);
  const showModal = ref(false);
  function selectSecond(value: any, index: number) {
    topTabActive.value = index;
    activedSeendData.value = value;
  }
  const pwdValue = ref();
  const showKeyboard = ref(false);
  const showPasswordInput = ref(true);
  const orderId = ref('');
  function buy(type: number) {
    // 没有输入金额
    if (!num.value) {
      NotifyWarn(i18nTranslate('Amout'));
      return;
    }
    // 余额不够
    if (num.value * 1 > assetsBalance.value) {
      NotifyWarn(i18nTranslate('Insufficientbalance'));
      return;
    }

    if (!qiehuan.value.name) {
      NotifyWarn(i18nTranslate('fail'));
      return;
    }
    if (Number(activedSeendData.value.minimum) > Number(num.value)) {
      NotifyWarn(i18nTranslate('Theminimumis') + activedSeendData.value.minimum);
      return;
    }
    confirmBuy(type);
    // showModal.value = true;
    // showKeyboard.value = true;
    // showPasswordInput.value = true;
  }
  const tradeList = ref<{ [xx: string]: any }>([]);
  const confirmBuy = (type: number) => {
    if (!dangqianjiage.value) {
      return;
    }
    let flag =
      qiehuan.value.type == 'CONTRACT' ? '1' : qiehuan.value.type == 'CARBON_TRADING' ? '2' : '0';
    const params = {
      contractType: type,
      currentPrice: dangqianjiage.value,
      deliveryAmount: num.value,
      deliveryTime: activedSeendData.value.id,
      member: getUserId(),
      pairsName: qiehuan.value.nickName || qiehuan.value.name,
      newPairsName: qiehuan.value.name,
      flag,
    };
    reauestSecondContractBetting.run(params);
  };
  const reauestSecondContractBetting = useRequest(secondContractBetting, {
    manual: true,
    onSuccess(data: any) {
      NotifySuccess(i18nTranslate('Successful'));
      (num.value = ''), (showModal.value = false);
      // if (!getWithExpiry('psd')) {
      //   setWithExpiry('psd', pwdValue.value, 1000 * 60 * 10);
      // }
      showPasswordInput.value = true;
      orderId.value = data;
    },
    onError() {
      showModal.value = false;
      showPasswordInput.value = true;
      return;
    },
  });
  function changeList(params: { [xx: string]: { flag: number } }) {
    let paramsKey = Object.keys(params) as string[];

    let huilvList: string[] = [];
    paramsKey.forEach((item) => {
      if (params[item].flag == 0) {
        huilvList.push(item);
      }
    });
    if (huilvList && huilvList.length) {
      let parms = huilvList.join(',').split('/').join('');
      queryOpenPriceparms(parms);
    }
    let customdate = new Date().getTime();
    clearInterval(listTimer.value);
    listTimer.value = null;

    listTimer.value = setInterval(() => {
      paramsKey.forEach((item) => {
        let aaa = item.split('-');
        let kinetype = '';
        for (const key in mapklinetype.value) {
          let condition = mapklinetype.value[key];
          if (condition == aaa[1]) {
            kinetype = key;
          }
        }
        let sendMsg = '';
        if (params[item].flag === 1) {
          sendMsg = `cryptoCurrency-["${aaa[0].split('/').join('')}"]`;
        } else {
          sendMsg = `initKline-${aaa[0]}-${kinetype}-${customdate - 1000 * 60 * 60}-${
            customdate + 1000 * 60 * 5
          }-${qiehuan.value.symbol}`;
        }
        if (!isContent()) return;
        jiadesocket.value.socketver.send(sendMsg);
      });
    }, 2000);
  }
  const requestuseGetBalances = useRequest(getBalances, {
    manual: true,
    onSuccess(data: any) {
      if (data.length) {
        assetsBalance.value = data[0].assetsBalance.toFixed(4);
      }
    },
  });
  const getBalance = () => {
    requestuseGetBalances.run({ member: getUserId(), currency: 'USD' });
  };
  useRequest(getUserInfo, {
    defaultParams: [{ member: getUserId() }],
    onSuccess(data: any) {
      userInfo.value = data;
    },
  });
  watch(showModal, () => {
    pwdValue.value = '';
  });
  const onBack = () => {
    router.push('/home');
  };
  const fullScreenShow = ref(false);
  const tabActive = ref(0);
  const activeList = ref<('1m' | '5m' | '15m' | '30m' | '1h' | '1d' | '1wk')[]>([
    '1m',
    '5m',
    '15m',
    '30m',
    '1h',
    '1d',
    '1wk',
  ]);
  const typeObj = ref<'1m' | '5m' | '15m' | '30m' | '1h' | '1d' | '1wk'>('1m');
  const handleTab = (item: '1m' | '5m' | '15m' | '30m' | '1h' | '1d' | '1wk', index: number) => {
    typeObj.value = item;
    tabActive.value = index;
  };
  function changezuihou(val: { [xx: string]: any }) {
    for (const key in val) {
      lastData.value[key] = val[key];
    }
    dangqianjiage.value = lastData.value.lastPrice;
  }
  const propsOptions = ref<{
    mainIndicator: string[];
    subIndicator: string[];
  }>({
    mainIndicator: [],
    subIndicator: [],
  });
</script>

<template>
  <div class="trade">
    <div class="trade_top_box">
      <div class="align-center trade_top_left">
        <var-icon name="chevron-left" :size="28" @click="onBack" />
        <div class="trade_top_img_box">
          <div class="img_box" v-if="!qiehuan.type && qiehuan.name">
            <div class="flag flag1">
              <img :src="$img(`country/${qiehuan.name.split('/')[0]}.png`)" alt="" />
            </div>
            <div class="flag flag2">
              <img :src="$img(`country/${qiehuan.name.split('/')[1]}.png`)" alt="" />
            </div>
          </div>
          <div class="img_box" v-else-if="qiehuan.type == 'CONTRACT'">
            <div class="flag1">
              <img
                :src="`https://s2.coinmarketcap.com/static/img/coins/64x64/${
                  imgsmap[qiehuan.name.split('/')[0]]
                }.png`"
                alt=""
              />
            </div>
          </div>
          <div class="img_box" v-else-if="qiehuan.type == 'CARBON_TRADING'">
            <div class="flag1">
              <img :src="`/${qiehuan.symbol}.png`" />
            </div>
          </div>
        </div>
        <p class="trade_top_name">
          {{ lastData.type == 'CARBON_TRADING' ? lastData.name + '/USD' : lastData.name }}
          <!-- {{ lastData.name || lastData.pairsName || lastData.nickName }} -->
          <!-- <span class="trade_top_unit" v-if="lastData.baseCurrencyName"
            >({{ lastData.mainCur }})</span
          > -->
        </p>
      </div>
      <TradePopup @change="changePopup">
        <div class="trade_top_right">
          <div class="arrow_icon">
            <img :src="$img('trade/arrow.png')" alt="" />
          </div>
          {{ $t('Exchange') }}
        </div>
      </TradePopup>
    </div>
    <div class="money_box"
      >{{ lastData.lastPrice
      }}<span class="money_num" :class="lastData.chg < 0 ? 'font_red' : 'font_green'"
        >{{ lastData.chg }} ({{ lastData.chgPct }})</span
      ></div
    >
    <div class="Kline_box">
      <Kline
        :propsOptions="propsOptions"
        :typeObj="typeObj"
        :queryData="qiehuan"
        :data="lastData"
        :fullScreen="fullScreenShow"
        @changezuihou="changezuihou"
      />
      <div class="list_box_tab">
        <span
          :class="tabActive === index ? 'tabs list_box_tab_active' : 'tabs'"
          v-for="(item, index) in activeList"
          :key="index"
          @click="handleTab(item, index)"
        >
          {{ item }}
        </span>
      </div>
    </div>
    <div class="trade_content">
      <div class="trade_content_top">
        <div class="trade_content_left">
          <div
            class="left_box"
            :class="index === topTabActive ? 'tab_active' : ''"
            v-for="(item, index) in secondscontractList"
            :key="index"
            @click="selectSecond(item, index)"
          >
            <p class="time">{{ item.seconds + item.secondsTime }}</p>
            <p class="pnl">{{ item.odds }}%</p>
            <p class="num">{{ item.minimum }}</p>
          </div>

          <div class="trade_input">
            <div class="input_box">
              <van-field class="input_number" v-model="num" type="number" />
            </div>
            <div class="available">
              <p>{{ $t('Available') }}</p>
              <p> {{ assetsBalance }} $</p>
            </div>
          </div>
        </div>
        <div class="trade_content_right">
          <div class="right_top">{{ $t('transaction') }}</div>
          <div class="right_list" v-for="(item, index) in tradeList" :key="index">
            <p class="text1">{{ $MDHms(item.time, 'HH:mm:ss ') }}</p>
            <p class="text1">{{ zhorderType(item.orderType) }}</p>
            <p class="text2" :class="item.type == 1 ? 'font_green' : 'font_red'">{{
              item.money
            }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="trade_button">
      <LargePrimaryButton block class="button" @click="buy(1)">{{
        $t('Buyup')
      }}</LargePrimaryButton>
      <LargeDangerButton block class="button" @click="buy(2)">{{
        $t('Buydown')
      }}</LargeDangerButton>
    </div>
    <!-- 历史记录 -->
    <div class="order_list">
      <van-tabs v-model:active="tab_active">
        <van-tab :title="$t('Orders')">
          <TradeOrders
            @change="changeList"
            @get-balance="getBalance"
            :currentPrice="currentPrice"
            :orderId="orderId"
          />
        </van-tab>
        <van-tab :title="$t('History')">
          <TradeHistory v-if="tab_active === 1" />
        </van-tab>
      </van-tabs>
    </div>
    <!-- 密码输入框 -->
    <var-popup class="popup-password-box" :show="showModal" teleport="body">
      <div class="popup-content">
        <div class="title">
          <span>{{ showPasswordInput ? $t('Password') : $t('Doyouconfirmtheorder') }}</span>
          <div class="close_icon" @click="showModal = false">
            <img :src="$img('common/close.png')" />
          </div>
        </div>
        <van-password-input
          :value="pwdValue"
          :gutter="10"
          v-if="showPasswordInput"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <!-- 数字键盘 -->
        <van-number-keyboard v-model="pwdValue" :show="showKeyboard" @blur="showKeyboard = false" />
        <var-space class="footer" direction="column" size="20">
          <!-- 确认按钮 -->
          <LargePrimaryButton
            block
            :loading="reauestSecondContractBetting.loading.value"
            @click="confirmBuy"
            >{{ $t('Confirm') }}
          </LargePrimaryButton>
        </var-space>
      </div>
    </var-popup>
  </div>
</template>

<style lang="scss" scoped>
  .trade {
    .font-color {
      color: #0063f5;
    }
    padding-bottom: 156px;
    .trade_top_box {
      padding: 20px 30px 20px 20px;
      @include align-center;
      justify-content: space-between;
      .trade_top_left {
        @include align-center;
        .trade_top_img_box {
          width: 48px;
          height: 48px;
          margin-right: 16px;
          .img_box {
            width: 56px;
            height: 56px;
            background: #242424;
            border-radius: 50%;
            margin-right: 10px;
            position: relative;
            .flag {
              width: 30px;
              height: 30px;
              position: absolute;
            }
            .flag1 {
              top: 8px;
              left: 10px;
            }
            .flag2 {
              top: 25px;
              left: 28px;
            }
          }
        }
        .trade_top_name {
          max-width: 70%;
          color: #f8f8f8;
          font-size: 32px;
          word-break: break-all;
        }
        .trade_top_unit {
          color: rgb(108, 117, 125);
          font-size: 20px;
          margin-left: 5px;
        }
      }

      .trade_top_right {
        @include align-center;
        height: 56px;
        color: #0063f5;
        font-size: 20px;
        border-radius: 96px;
        background: #0f1928;
        padding: 0 10px;
        .arrow_icon {
          width: 32px;
          height: 32px;
          margin-right: 8px;

          img {
            width: 100%;
            height: 100%;
          }
        }

        .trade_top_title {
          font-size: 46px;
          color: #ffffff;
          font-weight: 800;
          margin-right: 20px;
        }
      }
    }
    .money_box {
      padding: 10px 30px 20px 30px;
      color: rgb(255, 255, 255);
      font-size: 48px;
      .money_num {
        font-size: 32px;
        margin-left: 5px;
      }
    }
    .font_green {
      color: rgb(45, 189, 133);
    }
    .font_red {
      color: rgb(246, 69, 93);
    }

    .trade_content {
      padding: 30px;
      margin-top: 12px;
      .trade_content_top {
        display: flex;
        justify-content: space-between;
        height: 600px;
      }

      .trade_content_left {
        width: 58%;
        display: flex;
        flex-wrap: wrap;
        position: relative;

        .left_box {
          background: #242424;
          border-radius: 16px;
          height: 140px;
          width: 45%;
          @include center;
          margin-bottom: 20px;
          flex-direction: column;

          &.tab_active {
            border: 2px solid #0063f5;

            p {
              color: #0063f5;
            }
          }

          &:nth-child(2n) {
            margin-left: 20px;
          }

          .time {
            font-size: 30px;
          }

          .pnl {
            font-size: 22px;
            margin: 10px 0;
          }

          .num {
            font-size: 22px;
          }
        }
      }

      .trade_content_right {
        overflow: auto;
        width: 42%;
        height: 100%;

        .right_top {
          font-size: 26px;
        }

        .right_list {
          display: flex;
          justify-content: space-between;
          font-size: 22px;
          margin: 12px 0;

          .text1 {
            color: #ffffff;
          }
        }
      }

      .trade_input {
        .input_box {
          .input_number {
            height: 80px;
            border: 0;
            border-radius: 8px;
          }
        }
        .available {
          font-size: 26px;
          margin-top: 10px;
          display: flex;
          justify-content: space-between;
        }
      }
    }
    .order_list {
      margin-top: 12px;
    }
  }

  .trade_button {
    width: 100%;
    height: 156px;
    position: fixed;
    bottom: 0;
    background: rgb(26, 26, 26);
    display: flex;
    padding: 30px;
    z-index: 9;
    //box-shadow: 0px 0px 30px 0px rgb(238, 238, 238);
    .button {
      width: calc((100% - 30px) / 2);
    }
    .button:last-child {
      margin-left: 30px;
    }
  }
  .Kline_box {
    .list_box_tab {
      display: flex;
      overflow: auto;
      padding: 0 40px 22px;
      .tabs {
        padding: 10px 18px;
        font-size: 24px;
        color: #6c757d;
        display: flex;
        align-items: center;
        margin-right: 15px;
        height: 57px;
        border: 0;
        border-radius: 40px;
        background: #242424;
        &.list_box_tab_active {
          color: #0063f5;
          border-radius: 40px;
        }
      }
    }
  }
  .popup-password-box {
    .popup-content {
      padding: 30px 48px;
    }

    .title {
      font-weight: 600;
      margin-bottom: 68px;
      @include center;

      .close_icon {
        width: 22px;
        height: 22px;
        position: absolute;
        top: 33px;
        right: 40px;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .footer {
      width: 600px;
    }
  }
</style>
<style lang="scss">
  .trade {
    .van-cell {
      background: #242424;
      border-radius: 8px;
      border: 0;
    }
    .van-field__control {
      color: #ffffff;
    }
    .order_list {
      .van-tab__text--ellipsis {
        font-size: 30px;
        font-weight: 500;
        color: #999999;
      }
      .van-tabs__wrap {
        background: $body;
      }
      .van-tabs__nav {
        width: 60%;
        height: 65px;
        padding: 0 23px;
        background: $body;
      }

      .van-tab {
        background: #242424;
        border-radius: 10px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 28px;
        margin-right: 32px;
        padding: 0 45px;
        height: 62px;
      }
      .van-tab--active {
        background: #0f1928;
        .van-tab__text {
          color: rgb(0, 99, 245);
        }
      }
      .van-tabs__line {
        display: none;
      }
    }
  }

  .popup-password-box {
    border-radius: 16px;

    .van-password-input__security li {
      height: 80px;
      width: 80px;
      background: #f8f8f8;
      border-radius: 8px;
    }

    .var-button--primary {
      border-radius: 16px;
      background: #0063f5;
    }
  }
</style>
